import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { FormInstance } from 'antd/lib/form';
import {
  Modal,
  Button,
  Form,
  message,
  Input,
  Select,
  InputNumber,
  Space,
  Divider,
  Spin,
} from 'antd';
import PropTypes from 'prop-types';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { isNumber } from 'lodash';

const FormItem = Form.Item;
const mapStateToProps = (state: any) => ({
  serviceCapabilityDetail: state.serviceCapabilityDetail,
});
class _AddModal extends PureComponent<any, any> {
  formRef = React.createRef<FormInstance>();
  static contextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.array,
  };
  state = {
    serviceOpt: [],
    loading: false,
    accountData: JSON.parse(sessionStorage.getItem('serviceCapabilityDetailData') ?? '{}'),
    formLoading: false,
    contentFormData: [],
  };
  componentDidMount(): void {
    this.getServiceList();
  }
  componentDidUpdate(prevProps: any) {
    const { modalVisible, formData } = this.props;
    if (modalVisible && modalVisible !== prevProps.modalVisible) {
      this.formRef &&
        this.formRef.current?.setFieldsValue({
          ...formData,
        });
      formData.id && this.getKeyList();
    }
  }
  handleSubmit = () => {
    this.formRef.current?.submit();
  };

  onFinish = (values: any) => {
    const { dispatch, formData } = this.props;
    const { accountData, contentFormData } = this.state;
    const postData = {
      accountId: accountData.id,
      account: accountData.account,
      suppliersMap: accountData.suppliersMap,
      ...values,
    };
    let dType = 'serviceCapabilityDetail/postObjWithRes';
    let url = '/msaggregationmap/serviceconfigration/add'; //新增
    if (formData.id) {
      url = '/msaggregationmap/serviceconfigration/update';
      const delList = contentFormData.filter(
        (t: any) => (t.delFlag = 1) && values.content.every((y: any) => t.id !== y.id),
      );
      Object.assign(postData, {
        middleId: formData.middleId,
        serviceCode: formData.serviceCode,
        content: values.content.concat(delList),
      });
    }
    this.setState({
      loading: true,
    });
    dispatch({
      type: dType,
      payload: {
        url: url,
        ...postData,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          message.success('提交成功');
          this.close(true);
        }
        this.setState({
          loading: false,
        });
      },
    });
  };

  close = (refresh = false) => {
    const { closeModal } = this.props;
    this.formRef.current && this.formRef.current.resetFields();
    this.setState({ contentFormData: [] });
    closeModal(refresh);
  };

  getServiceList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'serviceCapabilityDetail/postObjWithRes',
      payload: {
        url: '/msaggregationmap/services/list',
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          this.setState({
            serviceOpt: res.data.map((t: any) => ({ label: t.serviceName, value: t.code })),
          });
        }
      },
    });
  };
  getKeyList = () => {
    const { dispatch, formData } = this.props;
    const { accountData } = this.state;
    this.setState({ formLoading: true });
    dispatch({
      type: 'serviceCapabilityDetail/postObjWithRes',
      payload: {
        url: '/msaggregationmap/serviceconfigration/detail',
        accountId: accountData.id,
        serviceCode: formData.serviceCode,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          this.formRef.current?.setFieldsValue({
            content: res.data?.content ?? [],
          });
          this.setState({ contentFormData: res.data?.content ?? [] });
        }
      },
    }).finally(() => this.setState({ formLoading: false }));
  };
  render() {
    const { formData, modalVisible } = this.props;
    const { loading, serviceOpt, formLoading } = this.state;
    const footer = (
      <div>
        <Button size="small" onClick={() => this.close()}>
          取消
        </Button>
        <Button
          size="small"
          disabled={formLoading}
          loading={loading}
          onClick={this.handleSubmit}
          type="primary"
        >
          确定
        </Button>
      </div>
    );
    const title = formData.id ? '编辑服务能力' : '配置服务能力';

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: {
          span: 6,
          // offset: 4,
        },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: {
          span: 14,
        },
        md: { span: 16 },
      },
    };

    return (
      <Modal
        title={title}
        footer={footer}
        visible={modalVisible}
        width={700}
        onCancel={() => this.close()}
      >
        <Spin spinning={formLoading}>
          <Form
            initialValues={{ content: [{}] }}
            style={{ marginTop: 12 }}
            ref={this.formRef}
            onFinish={this.onFinish}
          >
            <FormItem
              {...formItemLayout}
              label="服务能力"
              colon={false}
              name="serviceCode"
              rules={[
                {
                  required: true,
                  whitespace: true,
                  message: '请选择服务能力',
                },
              ]}
            >
              <Select
                options={serviceOpt}
                optionFilterProp="label"
                showSearch
                allowClear
                placeholder="请选择服务能力"
                disabled={!!formData.id}
              />
            </FormItem>
            <Divider dashed />
            <Form.List name="content">
              {(fields, { add, remove }) => (
                <>
                  {fields.map(field => (
                    <React.Fragment key={field.key}>
                      <Form.Item
                        rules={[
                          {
                            required: true,
                            whitespace: true,
                            message: '请输入key',
                          },
                        ]}
                        {...formItemLayout}
                        name={[field.name, 'secretKey']}
                        label="key"
                      >
                        <Input maxLength={100} />
                      </Form.Item>
                      <Form.Item
                        {...formItemLayout}
                        label="单日调用次数上限"
                        name={['content', field.name, 'daily']}
                        dependencies={[
                          ['content', field.name, 'dailyCallLimit'],
                          ['content', field.name, 'dailyErrorLimit'],
                        ]}
                        rules={[
                          {
                            validator: (rule, _value, callback) => {
                              const value = this.formRef.current?.getFieldValue([
                                'content',
                                field.name,
                              ]);
                              if (
                                isNumber(value.dailyCallLimit) &&
                                isNumber(value.dailyErrorLimit) &&
                                value.dailyCallLimit < value.dailyErrorLimit
                              ) {
                                callback('单日调用次数上限需大于等于单日调用错误次数上限');
                              }
                              callback();
                            },
                          },
                        ]}
                      >
                        <Space
                          key={field.key}
                          style={{ justifyContent: 'space-between', display: 'flex' }}
                          align="baseline"
                        >
                          <Form.Item name={[field.name, 'dailyCallLimit']}>
                            <InputNumber step={1} min={0} precision={0} />
                          </Form.Item>
                          <Form.Item
                            rules={[
                              {
                                required: true,
                                message: '请输入错误次数上限',
                              },
                            ]}
                            name={[field.name, 'dailyErrorLimit']}
                            label="单日调用错误次数上限"
                          >
                            <InputNumber step={1} min={0} precision={0} />
                          </Form.Item>
                          <MinusCircleOutlined
                            hidden={fields.length < 2}
                            onClick={() => {
                              remove(field.name);
                            }}
                            onPointerEnterCapture={undefined}
                            onPointerLeaveCapture={undefined}
                          />
                        </Space>
                      </Form.Item>
                    </React.Fragment>
                  ))}
                  <Form.Item>
                    <Button
                      type="dashed"
                      onClick={() => add()}
                      block
                      icon={
                        <PlusOutlined
                          onPointerEnterCapture={undefined}
                          onPointerLeaveCapture={undefined}
                        />
                      }
                    >
                      添加key
                    </Button>
                  </Form.Item>
                </>
              )}
            </Form.List>
          </Form>
        </Spin>
      </Modal>
    );
  }
}
export const AddModal = connect(mapStateToProps)(_AddModal);
